package com.zhmsky.config.shiro;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhmsky.entity.Role;
import com.zhmsky.entity.User;
import com.zhmsky.service.RoleService;
import com.zhmsky.service.UserService;
import com.zhmsky.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;

/**
 * @author zhmsky
 * @date 2021/12/5 11:23
 */
@Component
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    /**
     * 必须重写此方法，不然会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * @description 权限认证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("正在进行权限认证!");
        DecodedJWT tokenInfo = JwtUtils.getTokenInfo(principalCollection.toString());
        //从token中获取当前用户名
        String username = tokenInfo.getClaim("username").asString();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //该用户的角色
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userService.getOne(wrapper);
        String role = user.getRole();

        //根据角色名查询权限(模拟有两张表，user表和role表)
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("role", role);
        Role oneRole = roleService.getOne(roleQueryWrapper);
        String rolePermission = oneRole.getPermission();

        //在shiro中设置该用户的角色和权限，并封装作为authorizationInfo的参数
        HashSet<String> roleSet = new HashSet<>();
        HashSet<String> permissionSet = new HashSet<>();
        roleSet.add(role);
        permissionSet.add(rolePermission);
        authorizationInfo.setRoles(roleSet);
        authorizationInfo.setStringPermissions(permissionSet);
        return authorizationInfo;
    }

    /**
     * @description 用户名校验------用户认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("正在进行身份认证!");
        //获取Token
        String token =(String)authenticationToken.getCredentials();
        //从token中拿出username和数据库匹配
        DecodedJWT tokenInfo = JwtUtils.getTokenInfo(token);
        String username = tokenInfo.getClaim("username").asString();   //token中的username
        if(username==null||!JwtUtils.verify(token)){
            throw new AuthenticationException("token无效!");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userService.getOne(wrapper);
        if(user==null){
            throw new AuthenticationException("该用户不存在!");
        }
        Integer ban = user.getBan();
        if(ban==1){
            throw new AuthenticationException("该用户已被封号!");
        }
        return new SimpleAuthenticationInfo(token,token,"userRealm");
    }
}
